package com.vaadin.demo.jsdemo;

import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.ProgressBar;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Reindeer;

/**
 * 
 * @author u123183
 * 
 */
public class MyView extends VerticalLayout {
    public class Worker extends Thread {
        public final static int MAX = 10;
        int current = 1;

        public int getCurrent() {
            return current;
        }

        @Override
        public void run() {
            for (; current <= MAX; current++) {
                try {
                    Thread.sleep(1000);
                } catch (final InterruptedException e) {
                    e.printStackTrace();
                }
                // synchronized (UI.getCurrent()) {
                try {
                    UI.getCurrent().getSession().lock();
                    processed();
                } finally {
                    UI.getCurrent().getSession().unlock();
                }
            }
        }
    }
    private HorizontalLayout layout;
    private MyComponent myJsComponet;
    private ProgressBar progress;
    private Button startBtn;

    private Worker worker;

    public MyView() {
        bulidLayout();
    }

    private void bulidLayout() {
        layout = new HorizontalLayout();

        // Add a normal progress indicator
        progress = new ProgressBar();
        progress.setIndeterminate(true);
        progress.setEnabled(false);
        progress.setVisible(false);
        UI.getCurrent().setPollInterval(3000);
        layout.addComponent(progress);
        layout.setComponentAlignment(progress, Alignment.BOTTOM_LEFT);

        startBtn = new Button("Start", new Button.ClickListener() {
            @Override
            public void buttonClick(final ClickEvent event) {
                worker = new Worker();
                worker.start();
                progress.setEnabled(true);
                progress.setVisible(true);
                startBtn.setEnabled(false);
            }
        });
        startBtn.setStyleName(Reindeer.BUTTON_SMALL);
        layout.addComponent(startBtn);
        layout.setComponentAlignment(startBtn, Alignment.BOTTOM_RIGHT);

        myJsComponet = new MyComponent();

        this.setSpacing(true);
        this.addComponent(layout);
        this.addComponent(myJsComponet);
    }

    public final void processed() {
        final int i = worker.getCurrent();
        progress.setEnabled(true);
        if (i == Worker.MAX) {
            startBtn.setEnabled(true);
            startBtn.setVisible(true);
            layout.removeComponent(progress);
        }
        myJsComponet.setValue("" + i);
    }
}
